<template>
  <div
    ref="chartRef"
    :style="{ height: height }"
  ></div>
</template>
<script>
import * as echarts from 'echarts'
import { addListener, removeListener } from 'resize-detector'
import debounce from 'lodash/debounce'
export default {
  props: {
    height: {
      type: String,
      default: '350px'
    },
    option: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    // option: {
    //   handler(val) {
    //     this.myChart.setOption(val)
    //   },
    //   deep: true
    // }
    option(val) {
      this.myChart.setOption(val)
    }
  },
  created() {
    // 防抖
    this.resize = debounce(this.resize, 1000)
  },
  mounted() {
    this.renderChart()
    // 监听数据更新之后再执行改变图表的大小
    addListener(this.$refs.chartRef, this.resize)
  },
  methods: {
    renderChart() {
      this.myChart = echarts.init(this.$refs.chartRef)
      this.myChart.setOption(this.option)
    },
    resize() {
      // console.log('resize')
      this.myChart.resize()
    }
  },
  beforeDestroy() {
    // 当页面销毁释放监听的函数
    removeListener(this.$refs.chartRef, this.resize)
    // 释放数据防止内存泄露
    this.myChart.dispose()
    this.myChart = null
  }
}
</script>
<style lang="scss" scoped></style>
